package com.ssm.util.test.encrypt;

import java.security.MessageDigest;

import org.apache.commons.codec.digest.DigestUtils;

/**
 * 加密算法 DigestUtils 需要引入 commons-codec.jar  常见md系列加密
 * 
 * @author Administrator
 *
 */
public class Md5Util {

	private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
			'e', 'f' };

	// md5加密 密文16进制
	public static String md5Hex(String text, String input_charset) throws Exception {
		return DigestUtils.md5Hex(getContentBytes(text, input_charset));
	}

	public static String md5Hex1(String text, String input_charset) throws Exception {
		MessageDigest md = MessageDigest.getInstance("MD5");
		md.update(text.getBytes(input_charset));
		String md5 = getFormattedText(md.digest());
		return md5;
	}

	private static byte[] getContentBytes(String content, String charset) throws Exception {
		if (charset == null || "".equals(charset)) {
			return content.getBytes();
		}
		try {
			return content.getBytes(charset);
		} catch (Exception e) {
			throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
		}
	}

	// 加密算法 把密文转成16进制的字符串形式
	public static String getFormattedText(byte[] bytes) throws Exception {
		int len = bytes.length;
		StringBuilder buf = new StringBuilder(len * 2);
		for (int j = 0; j < len; j++) {
			buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
			buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
		}
		return buf.toString();
	}

	public static void main(String[] args) throws Exception {
		String str = "123456";
		// md5加密
		System.out.println("md5Hex:" + md5Hex(str, "utf-8"));
		System.out.println("md5Hex:" + md5Hex1(str, "utf-8"));
		
	}

}
